package com.gimi.cloud.bbp.manage.service.sys.impl;

import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.utils.NumberUtil;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.dao.dao.sys.SysRoleDao;
import com.gimi.cloud.bbp.dto.sys.SysRoleDTO;
import com.gimi.cloud.bbp.entity.sys.SysRoleEntity;
import com.gimi.cloud.bbp.dto.params.ModifySysRoleParam;
import com.gimi.cloud.bbp.dto.params.RoleListParams;
import com.gimi.cloud.bbp.dto.params.RoleSingleParams;
import com.gimi.cloud.bbp.manage.service.sys.RoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by shazhiwei on 2017/12/15.
 */
@Service
public class RoleServiceImpl implements RoleService {
    private final SysRoleDao roleDao;

    @Autowired
    public RoleServiceImpl(SysRoleDao roleDao){
        this.roleDao = roleDao;
    }

    @Override
    public List<SysRoleDTO> getRoleList() {
        return roleDao.getRoleList();
    }

    @Override
    public List<SysRoleDTO> getRolePageList(RoleListParams params) {
        String name = params.getName();
        Integer size = params.getPageSize();
        Integer offset = (params.getCurrentPage() - 1) * size;
        String sql = "";
        if(!StringUtil.isBlank(name)){
            sql = String.format("SELECT * FROM sys_role WHERE is_delete = 0 AND (ro_name = '%s' or ro_alias = '%s') ORDER BY add_time DESC LIMIT %d,%d;",name,name,offset,size);
        }else{
            sql = String.format("SELECT * FROM sys_role ORDER BY add_time DESC LIMIT %d,%d;",offset,size);
        }
        List<SysRoleDTO> result = roleDao.queryPage(sql);
        return result;
    }

    @Override
    public Long getCount() {
        return roleDao.getCount();
    }

    @Override
    public SysRoleDTO getRoleSingle(RoleSingleParams params) {
        return roleDao.selectById(NumberUtil.getInt(params.getRoleId()));
    }

    @Override
    public ModifySysRoleParam addRole(ModifySysRoleParam params) {
        SysRoleEntity roleEntity = new SysRoleEntity();
        BeanUtils.copyProperties(params,roleEntity);
        roleDao.insertSelective(roleEntity);
        params.setResponseCodeEnum(ResponseCodeEnum.SUCCESSED);
        return params;
    }

    @Override
    public ModifySysRoleParam editRole(ModifySysRoleParam params) {
        SysRoleEntity roleEntity = new SysRoleEntity();
        BeanUtils.copyProperties(params,roleEntity);
        roleDao.updateByPrimaryKeySelective(roleEntity);
        params.setResponseCodeEnum(ResponseCodeEnum.SUCCESSED);
        return params;
    }

}
